package cn.dawn.webcollector.generator;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import cn.dawn.webcollector.model.CrawlDatum;
import cn.dawn.webcollector.util.BerkeleyDBUtils;
import cn.dawn.webcollector.util.Config;

import com.sleepycat.je.Database;
import com.sleepycat.je.DatabaseConfig;
import com.sleepycat.je.Environment;

/**
 * 
 * <p>种子注入器</p>
 * <p>种子注入器，负责第一轮爬取时，向CrawlDB中提交爬取任务。在断点续爬的时候，不需要通过Injector向CrawlDatum注入种子，因为CrawlDB中已有爬取任务。</p>
 * @Copyright:Copyright (c) 2015
 * @Author:wangxiao
 * @Version:1.0
 * @Time:2015年10月10日
 */
public class Injector {

	Environment env;

	public Injector(Environment env) {
		this.env = env;
	}

	public void inject(String seed) throws UnsupportedEncodingException {
		Database database = env.openDatabase(null, Config.BDB_CRAWLDB, BerkeleyDBUtils.defaultDBConfig);
		CrawlDatum datum = new CrawlDatum(seed, CrawlDatum.STATUS_DB_INJECTED);
		database.put(null, datum.getKey(), datum.getValue());
		database.sync();
		database.close();
	}

	public void inject(ArrayList<String> seeds) throws UnsupportedEncodingException {
		DatabaseConfig databaseConfig = new DatabaseConfig();
		databaseConfig.setAllowCreate(true);
		databaseConfig.setDeferredWrite(true);
		Database database = env.openDatabase(null, Config.BDB_CRAWLDB, databaseConfig);
		for (String seed : seeds) {
			CrawlDatum datum = new CrawlDatum(seed, CrawlDatum.STATUS_DB_INJECTED);
			database.put(null, datum.getKey(), datum.getValue());
		}
		database.sync();
		database.close();
	}
}
